﻿using System;
using System.Drawing;
using System.Windows.Forms;
using AyuBookmark.Common.Models;
using AyuBookmark.WinForm.Controls;
using AyuBookmark.WinForm.Dialogs;

namespace AyuBookmark.WinForm
{
    /// <summary>
    /// 主窗体 - 书签管理系统的核心界面
    /// </summary>
    public partial class MainForm : Form
    {
        private SplitContainer splitContainer;
        private TreeView treeCategories;
        private BookmarkListView bookmarkListView;
        private ToolStrip toolStrip;
        private StatusStrip statusStrip;
        private MenuStrip menuStrip;
        private SearchBox searchBox;

        public MainForm()
        {
            InitializeComponent();
            InitializeUI();
            LoadSampleData();
        }

        private void InitializeComponent()
        {
            // 窗体基础设置
            this.SuspendLayout();
            this.Text = "AyuBookmark - 书签管理";
            this.StartPosition = FormStartPosition.CenterScreen;
            this.WindowState = FormWindowState.Maximized;
            this.MinimumSize = new Size(800, 600);

            // 主菜单
            this.menuStrip = new MenuStrip();
            this.menuStrip.Dock = DockStyle.Top;

            // 文件菜单
            var fileMenu = new ToolStripMenuItem("文件(&F)");
            fileMenu.DropDownItems.Add("导入/导出(&I)...", null, (s, e) =>
                ((Form)(new ImportExportDialog())).ShowDialog(this)  );
            fileMenu.DropDownItems.Add("退出(&X)", null, (s, e) => this.Close());

            // 编辑菜单
            var editMenu = new ToolStripMenuItem("编辑(&E)");
            editMenu.DropDownItems.Add("新增书签(&N)", null, OnAddBookmark);
            editMenu.DropDownItems.Add("编辑书签(&E)", null, OnEditBookmark);
            editMenu.DropDownItems.Add("删除书签(&D)", null, OnDeleteBookmark);

            // 视图菜单
            var viewMenu = new ToolStripMenuItem("视图(&V)");
            viewMenu.DropDownItems.Add("刷新(&R)", null, OnRefresh);

            // 帮助菜单
            var helpMenu = new ToolStripMenuItem("帮助(&H)");
            helpMenu.DropDownItems.Add("关于(&A)...", null, (s, e) =>
                new AboutDialog().ShowDialog(this));

            this.menuStrip.Items.AddRange(new ToolStripItem[] { fileMenu, editMenu, viewMenu, helpMenu });

            // 工具栏
            this.toolStrip = new ToolStrip();
            this.toolStrip.Dock = DockStyle.Top;
            this.toolStrip.Items.Add("新增", null, OnAddBookmark);
            this.toolStrip.Items.Add("编辑", null, OnEditBookmark);
            this.toolStrip.Items.Add("删除", null, OnDeleteBookmark);
            this.toolStrip.Items.Add(new ToolStripSeparator());
            this.toolStrip.Items.Add("刷新", null, OnRefresh);

            // 状态栏
            this.statusStrip = new StatusStrip();
            this.statusStrip.Dock = DockStyle.Bottom;
            this.statusStrip.Items.Add(new ToolStripStatusLabel
            {
                Text = "就绪",
                Spring = true,
                TextAlign = ContentAlignment.MiddleLeft
            });

            // 搜索框
            this.searchBox = new SearchBox();
            this.searchBox.Dock = DockStyle.Top;
            this.searchBox.SearchTriggered += OnSearchTriggered;

            // 分割容器
            this.splitContainer = new SplitContainer();
            this.splitContainer.Dock = DockStyle.Fill;
            this.splitContainer.SplitterDistance = 200;
            this.splitContainer.FixedPanel = FixedPanel.Panel1;

            // 分类树
            this.treeCategories = new TreeView();
            this.treeCategories.Dock = DockStyle.Fill;
            this.treeCategories.HideSelection = false;
            this.treeCategories.AfterSelect += OnCategorySelected;

            // 书签列表
            this.bookmarkListView = new BookmarkListView();
            this.bookmarkListView.Dock = DockStyle.Fill;
            this.bookmarkListView.ItemClicked += OnBookmarkClicked;
            this.bookmarkListView.ItemDoubleClicked += OnBookmarkDoubleClicked;

            // 添加控件到分割容器
            this.splitContainer.Panel1.Controls.Add(this.treeCategories);
            this.splitContainer.Panel2.Controls.Add(this.bookmarkListView);

            // 添加主控件
            this.Controls.Add(this.splitContainer);
            this.Controls.Add(this.searchBox);
            this.Controls.Add(this.toolStrip);
            this.Controls.Add(this.menuStrip);
            this.Controls.Add(this.statusStrip);

            this.MainMenuStrip = this.menuStrip;
            this.ResumeLayout(false);
            this.PerformLayout();
        }

        private void InitializeUI()
        {
            // 设置树视图图标
            ImageList treeImages = new ImageList();
            treeImages.Images.Add("folder", SystemIcons./*Folder*/Hand);
            treeImages.Images.Add("category", SystemIcons.Information);
            this.treeCategories.ImageList = treeImages;

            // 设置书签列表视图
            this.bookmarkListView.SetColumns(new[]
            {
                new BookmarkListView.ColumnInfo("标题", 200),
                new BookmarkListView.ColumnInfo("URL", 300),
                new BookmarkListView.ColumnInfo("描述", 150),
                new BookmarkListView.ColumnInfo("创建时间", 120)
            });
        }

        private void LoadSampleData()
        {
            // 加载示例分类
            this.treeCategories.Nodes.Clear();

            var rootNode = new TreeNode("所有书签", 0, 0);
            rootNode.Nodes.Add(new TreeNode("工作", 1, 1));
            rootNode.Nodes.Add(new TreeNode("学习", 1, 1));
            rootNode.Nodes.Add(new TreeNode("娱乐", 1, 1));
            this.treeCategories.Nodes.Add(rootNode);
            rootNode.Expand();

            // 加载示例书签
            var sampleBookmarks = new[]
            {
                new Bookmark
                {
                    Title = "GitHub",
                    Url = "https://github.com",
                    Description = "代码托管平台"
                },
                new Bookmark
                {
                    Title = "Stack Overflow",
                    Url = "https://stackoverflow.com",
                    Description = "开发者问答社区"
                }
            };

            this.bookmarkListView.SetDataSource(sampleBookmarks);
            UpdateStatus($"已加载 {sampleBookmarks.Length} 条书签");
        }

        #region 事件处理方法
        private void OnCategorySelected(object sender, TreeViewEventArgs e)
        {
            UpdateStatus($"已选择分类: {e.Node.Text}");
        }

        private void OnBookmarkClicked(object sender, Bookmark bookmark)
        {
            UpdateStatus($"已选择书签: {bookmark.Title}");
        }

        private void OnBookmarkDoubleClicked(object sender, Bookmark bookmark)
        {
            try
            {
                System.Diagnostics.Process.Start(bookmark.Url);
                UpdateStatus($"正在打开: {bookmark.Title}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开链接: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OnSearchTriggered(object sender, string keyword)
        {
            UpdateStatus($"正在搜索: {keyword}");
        }

        private void OnAddBookmark(object sender, EventArgs e)
        {
            using (var dialog = new BookmarkEditor/*Dialog*/())
            {
                if (dialog.ShowDialog(this) == DialogResult.OK)
                {
                    UpdateStatus("已添加新书签");
                }
            }
        }

        private void OnEditBookmark(object sender, EventArgs e)
        {
            var selected = bookmarkListView.SelectedBookmark;
            if (selected == null)
            {
                MessageBox.Show("请先选择要编辑的书签", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            using (var dialog = new BookmarkEditor/*Dialog*/(selected))
            {
                if (dialog.ShowDialog(this) == DialogResult.OK)
                {
                    UpdateStatus("已更新书签");
                }
            }
        }

        private void OnDeleteBookmark(object sender, EventArgs e)
        {
            var selected = bookmarkListView.SelectedBookmark;
            if (selected == null)
            {
                MessageBox.Show("请先选择要删除的书签", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show($"确定要删除书签 '{selected.Title}' 吗?", "确认删除",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                UpdateStatus("已删除书签");
            }
        }

        private void OnRefresh(object sender, EventArgs e)
        {
            UpdateStatus("已刷新数据");
        }

        private void UpdateStatus(string message)
        {
            this.statusStrip.Items[0].Text = message;
        }
        #endregion

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定要退出程序吗?", "确认退出",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            {
                e.Cancel = true;
            }
            base.OnFormClosing(e);
        }
    }

    /// <summary>
    /// 自定义书签列表视图
    /// </summary>
    public class BookmarkListView : ListView
    {
        public class ColumnInfo
        {
            public string Text { get; set; }
            public int Width { get; set; }

            public ColumnInfo(string text, int width)
            {
                Text = text;
                Width = width;
            }
        }

        // 事件定义
        public event EventHandler<Bookmark> ItemClicked;
        public event EventHandler<Bookmark> ItemDoubleClicked;

        private List<Bookmark> _dataSource;

        public BookmarkListView()
        {
            this.View = View.Details;
            this.FullRowSelect = true;
            this.MultiSelect = false;
        }

        public void SetColumns(ColumnInfo[] columns)
        {
            this.Columns.Clear();
            foreach (var col in columns)
            {
                this.Columns.Add(col.Text, col.Width);
            }
        }

        public void SetDataSource(IEnumerable<Bookmark> bookmarks)
        {
            this.Items.Clear();
            _dataSource = new List<Bookmark>(bookmarks);

            foreach (var b in _dataSource)
            {
                var item = new ListViewItem(b.Title);
                item.SubItems.Add(b.Url);
                item.SubItems.Add(b.Description ?? "");
                item.SubItems.Add(DateTime.Now.ToString("yyyy-MM-dd"));
                item.Tag = b;
                this.Items.Add(item);
            }
        }

        public Bookmark SelectedBookmark => this.SelectedItems.Count > 0
            ? this.SelectedItems[0].Tag as Bookmark
            : null;

        protected override void OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e)
        {
            base.OnItemSelectionChanged(e);
            if (e.IsSelected)
            {
                ItemClicked?.Invoke(this, e.Item.Tag as Bookmark);
            }
        }

        protected override void OnDoubleClick(EventArgs e)
        {
            base.OnDoubleClick(e);
            if (this.SelectedItems.Count > 0)
            {
                ItemDoubleClicked?.Invoke(this, this.SelectedItems[0].Tag as Bookmark);
            }
        }
    }
}